//
//  NumField.swift
//  Aiwei
//
//  Created by zhu xietong on 2017/11/8.
//  Copyright © 2017年 zhu xietong. All rights reserved.
//

import UIKit
import Eelay


extension TP{
    public static var NumLimit = "NumLimit"
}

public struct NumLimit {
    public var min:Int = 1
    public var max:Int = 10000
    public var maxMask = "数量超过限制".loc
    public var minMask = "无效数量".loc
    
    public var jsonValue:String{
        get{
            var dict = [String:Any]()
            dict["min"] = "\(self.min)"
            dict["max"] = "\(self.min)"
            dict["minMask"] = "\(self.minMask)"
            dict["maxMask"] = "\(self.maxMask)"
            return dict.rawJson ?? "{}"
        }
    }
    public init() {
        
    }
    
    public init(min:Int=1,minMask:String="数量无效".loc,max:Int=100000,maxMask:String="数量超过限制".loc) {
        self.min = min
        self.max = max
        self.maxMask = maxMask
        self.minMask = minMask
    }
    
    public init(json:String) {
        let dict = json.JsonDictionary ?? NSMutableDictionary()
        
        self.min = dict[int:"min",0]
        self.max = dict[int:"max",self.max]
        self.maxMask = dict["maxMask",""]
        self.minMask = dict["minMask",""]
        
    }

}


public class NumAlertField: FieldView {
    public let valueL = UILabel()
    open override func addLayoutRules() {
        let bt = UIButton()
        self.eelay = [
            [valueL,[ee.T.L.B.R]],
            [bt,[ee.T.L.B.R]],
        ]
        
        _ = valueL.ui.cl_666.font14
        self.isUserInteractionEnabled = true
        bt.addTarget(self, action: #selector(selectAction), for: .touchUpInside)
    }
    
    override open func get_string_value() -> String {
        return self.mo.model[FK.value,"1"]
    }
    
    @objc open func selectAction()
    {
        if mo.model[FK.editble,"YES"] == "NO"
        {
            return
        }
        NotificationCenter.default.post(name: NSNotification.Name(rawValue: FK.SaveJoFormNotify), object: nil)
        weak var wself = self
        let ctr = NumPopSelector()
        ctr.value = mo.model[int:FK.value,1]
        ctr.selectValue = {
            wself?.mo.model[FK.value] = "\($0)"
            wself?.mo_model_reload()
        }
        self.controller?.present(ctr, animated: false, completion: {
            
        })
    }
    
    open override func mo_model_reload() {
        
        let value = Int(mo.model[FK.value,""])
        if let _value = value
        {
            self.valueL.text = "\(_value)"
            valueL.ui.font(font: FieldView.valueStyle.font).text(color: FieldView.valueStyle.color)
        }
        else
        {
            valueL.ui.font(font: FieldView.holderStyle.font).text(color: FieldView.holderStyle.color).text(mo.model[FK.placeholder,""])
        }
    }
}
